<template>
  <PageContainer 
    :show-nav-bar="true"
    :show-back="false"
    :title="h5Title"
    :title-color="h5TitleColor"
    :background-color="'#ffffff'"
  >
    <!-- 头部背景区域 -->
    <view class="header-bg" :style="{ backgroundImage: `url(${backgroundImageUrl})` }">
      <!-- 关闭按钮 -->
      <view class="close-btn" @click="handleClose">
        <image class="close-icon" :src="getImageUrl('/static/Images/common/Guanbihei.png')" mode="aspectFit"></image>
      </view>
      <!-- 欢迎文字 -->
      <view class="welcome-section">
        <text class="welcome-text">您好，</text>
        <text class="welcome-text">欢迎来到充值平台</text>
      </view>
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view class="login-tab" :class="{ active: loginMode === 'sms' }" @click="loginMode = 'sms'">验证码登录</view>
        <view class="login-tab" :class="{ active: loginMode === 'password' }" @click="loginMode = 'password'">密码登录</view>
      </view>

      <!-- 通用：手机号输入框 -->
      <view class="input-group">
        <input 
          class="input-field" 
          type="number" 
          placeholder="请输入手机号" 
          v-model="phoneNumber"
          maxlength="11"
        />
      </view>

      <!-- 短信验证码登录表单 -->
      <view v-if="loginMode === 'sms'">
        <view class="input-group verification-group">
          <input 
            class="input-field verification-input" 
            type="number" 
            placeholder="请输入验证码" 
            v-model="verificationCode"
            maxlength="6"
          />
          <view class="send-code-btn" @click="sendVerificationCode" :class="{ disabled: countdown > 0 }">
            <text class="send-code-text">{{ countdown > 0 ? `${countdown}s` : '发送验证码' }}</text>
          </view>
        </view>
      </view>

      <!-- 密码登录表单 -->
      <view v-else>
        <view class="input-group">
          <input
            class="input-field"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="password"
            maxlength="20"
          />
        </view>
      </view>

      <!-- 同意条款 -->
      <view class="agreement-section">
        <view class="checkbox-wrapper" @click="toggleAgreement">
          <view class="checkbox" :class="{ checked: isAgreed }">
            <view class="checkbox-inner" v-if="isAgreed"></view>
          </view>
          <text class="agreement-text">我已阅读并同意</text>
          <text class="agreement-link" @click.stop="showServiceAgreement">服务协议</text>
          <text class="agreement-text">、</text>
          <text class="agreement-link" @click.stop="showPrivacyPolicy">隐私权政策</text>
        </view>
      </view>

      <!-- 注册提示 -->
      <!-- <view class="register-tip">
        <text class="register-text">没有账号？</text>
        <text class="register-link" @click="goToRegister">立即注册</text>
      </view> -->

      <!-- 登录按钮 -->
      <view class="login-btn" @click="handleLogin" :class="{ disabled: !canLogin }">
        <text class="login-btn-text">{{ loginMode === 'sms' ? '登录' : '登录' }}</text>
      </view>
    </view>
    
    <!-- 第三方登录 -->
    <view class="third-party-section">
      <text class="third-party-title">使用第三方账号登录</text>
      <view class="third-party-buttons">
        <view class="third-party-btn" @click="handleWechatLogin">
          <image class="third-party-icon" :src="getImageUrl('/static/Images/common/Wechat.png')" mode="aspectFit"></image>
        </view>
        <view class="third-party-btn" @click="handleQQLogin">
          <image class="third-party-icon" :src="getImageUrl('/static/Images/common/QQ.png')" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    </view>  
  </PageContainer>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { smsApi, userApi } from '@/utils/api';
import { getImageUrl } from '@/config/api';
import { validatePhone, validateCode } from '@/utils/validate';
import { userStorage } from '@/utils/storage';

// 响应式数据
const phoneNumber = ref('');
const verificationCode = ref('');
const password = ref('');
const showPassword = ref(false);
const loginMode = ref('sms'); // sms | password
const isAgreed = ref(false);
const countdown = ref(0);
let countdownTimer = null;

// 计算属性
const canLogin = computed(() => {
  if (!validatePhone(phoneNumber.value) || !isAgreed.value) return false;
  return loginMode.value === 'sms'
    ? /^(?:\d{4}|\d{6})$/.test(verificationCode.value)
    : password.value && password.value.length >= 6;
});

// H5平台标题显示
const h5Title = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '登录' : '';
});

const h5TitleColor = computed(() => {
  // 使用运行时平台检测
  const platform = uni.getSystemInfoSync().platform;
  const isH5 = platform === 'devtools' || typeof window !== 'undefined';
  return isH5 ? '#000000' : '';
});

// 背景图片URL
const backgroundImageUrl = computed(() => {
  return getImageUrl('/static/Images/common/Loginbj.png');
});

// 关闭页面
const handleClose = () => {
  uni.navigateBack();
};

// 切换同意状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value;
};

// 发送验证码
const sendVerificationCode = async () => {
  if (countdown.value > 0) return;
  
  if (!validatePhone(phoneNumber.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 显示加载状态
    uni.showLoading({
      title: '发送中...'
    });
    
    // 调用发送验证码API
    const response = await smsApi.sendCode(phoneNumber.value);
    
    uni.hideLoading();
    
    // 发送成功，开始倒计时
    countdown.value = 60;
    countdownTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownTimer);
      }
    }, 1000);
    
    uni.showToast({
      title: response.msg || '验证码已发送',
      icon: 'success'
    });
    
  } catch (error) {
    uni.hideLoading();
    console.error('发送验证码失败:', error);
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none'
    });
  }
};

// 登录处理
const handleLogin = async () => {
  if (!canLogin.value) return;
  
  try {
    uni.showLoading({ title: '登录中...' });
    let response;
    if (loginMode.value === 'sms') {
      // 短信验证码登录：mobile + msgCode
      response = await userApi.loginByMsgCode(phoneNumber.value, verificationCode.value);
    } else {
      // 密码登录：mobile + pwd
      response = await userApi.login(phoneNumber.value, password.value);
    }

    uni.hideLoading();

    // 兼容两种返回结构：
    // 1) { success: true, token: '...' }
    // 2) { code: 1, msg: '登录成功', data: 'token' }
    const successFlag = (response && response.success === true) || (response && (response.code === 1 || response.code === 200));
    
    if (successFlag) {
      // 获取token
      const token = response.token || response.data;
      
      if (token) {
        // 保存token
        userStorage.setToken(token);
        
        // 获取用户信息并保存到全局
        try {
          const userInfoResponse = await userApi.getUserInfo();
          if (userInfoResponse && userInfoResponse.data) {
            userStorage.setUserInfo(userInfoResponse.data);
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
          // 即使获取用户信息失败，也不影响登录流程
        }
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        throw new Error('登录失败：未获取到有效token');
      }
    } else {
      throw new Error(response?.msg || '登录失败');
    }

  } catch (error) {
    uni.hideLoading();
    console.error('登录失败:', error);
    uni.showToast({ title: error.message || '登录失败，请重试', icon: 'none' });
  }
};

// 检测是否为微信内置浏览器
const isWechatBrowser = () => {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('micromessenger');
};

// 微信登录
const handleWechatLogin = () => {
  uni.navigateTo({
    url: '/pages/login/wxlogin'
  });
};

// QQ登录
const handleQQLogin = () => {
  uni.showToast({
    title: 'QQ登录功能开发中',
    icon: 'none'
  });
};

// 显示服务协议
const showServiceAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/service'
  });
};

// 显示隐私政策
const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy'
  });
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register'
  });
};

// 页面加载时检测微信浏览器
onMounted(() => {
  // 检测是否为微信内置浏览器，如果是则自动跳转到微信登录页面
  if (isWechatBrowser()) {
    uni.navigateTo({
      url: '/pages/login/wxlogin'
    });
  }
});

// 页面卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="scss" scoped>
/* 头部背景区域 */
.header-bg {
  position: relative;
  overflow: hidden;
  background-size: 120% 100%;
  background-position: center;
  background-repeat: no-repeat;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  width: 20rpx;
  height: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  left: 1rem;
  top: 1rem;
}

.close-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 欢迎区域 */
.welcome-section {
  padding: 3.8rem 1.85rem;
  margin-top: 5rem;
}

.welcome-text {
  display: block;
  font-size: 48rpx;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
}

/* 表单区域 */
.form-section {
  flex: 1;
  padding: 0 60rpx;
}

.input-group {
  margin-bottom: 40rpx;
  position: relative;
}

.input-field {
  height: 100rpx;
  background-color: #f0f0f0;
  border-radius: 12rpx;
  padding: 0 30rpx;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
}

.input-field::placeholder {
  color: #999;
}

/* 验证码输入组 */
.verification-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.verification-input {
  flex: 1;
}

.send-code-btn {
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #ff4757;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200rpx;
}

.send-code-btn.disabled {
  background-color: #ccc;
}

.send-code-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

/* 同意条款 */
.agreement-section {
  margin: 60rpx 0 80rpx;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 50%;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.checkbox.checked {
  border-color: #ff4757;
  background-color: #ff4757;
}

.checkbox-inner {
  width: 12rpx;
  height: 12rpx;
  background-color: #fff;
  border-radius: 50%;
}

.agreement-text {
  font-size: 26rpx;
  color: #666;
}

.agreement-link {
  font-size: 26rpx;
  color: #ff4757;
  text-decoration: underline;
}

/* 注册提示 */
.register-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.register-text {
  font-size: 28rpx;
  color: #666;
  margin-right: 8rpx;
}

.register-link {
  font-size: 28rpx;
  color: #ff4757;
  font-weight: 500;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 100rpx;
  background-color: #ff4757;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;
}

.login-btn.disabled {
  background-color: #ccc;
}

.login-btn-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

/* 第三方登录 */
.third-party-section {
  padding: 0 60rpx 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-party-title {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.third-party-buttons {
  display: flex;
  gap: 60rpx;
}

.third-party-btn {
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.third-party-icon {
  width: 80rpx;
  height: 80rpx;
}

.login-tabs {
  display: flex;
  gap: 24rpx;
  margin-bottom: 32rpx;
}
.login-tab {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #666;
  font-size: 28rpx;
}
.login-tab.active {
  background-color: #ff4757;
  color: #fff;
}
</style>